#!/usr/bin/python

#this is the main user interface
from Tkinter import *
import tkFont
import tkMessageBox
import grabrss
import getItem
import re
import Image, ImageTk
import webbrowser



GOAGENT = '127.0.1:8087'
WCHAMBER = '127.0.1:1998'
globalproxy = '127.0.1:1998'


"""	

#this is how to query piratebay
#http://thepiratebay.se/search/jersey%20shore/0/7/0

#this will go via west chamber

GOAGENT = '1270.0.1:8087'
WCHAMBER = '1270.0.1:1998'

proxy = urllib2.ProxyHandler({'http': '127.0.0.1:1998'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
f = urllib2.urlopen('http://www.google.com')
print f.read()



for c in colours:
    Label(text=c, relief=RIDGE,width=15).grid(row=r,column=0)
    Entry(bg=c, relief=SUNKEN,width=10).grid(row=r,column=1)
    r = r + 1




# this is how to access system clipboard

from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.destroy()



		image1 = Image.open(f)
        root.geometry('%dx%d' % (image1.size[0],image1.size[1]))
        tkpi = ImageTk.PhotoImage(image1)
        label_image = Tkinter.Label(root, image=tkpi)
        label_image.place(x=0,y=0,width=image1.size[0],height=image1.size[1])

"""

class myApp ():

	def __init__(self, root):

		global GOAGENT
		global WCHAMBER
		global globalproxy

		self.r = root
		self.ifProxy = IntVar()


		mainframe = Frame(root)
		mainframe.grid(column=0, row=0, sticky=(N, W, E, S))


		#pincture for top baner
		titleimage = Image.open("dd.jpg")
		photo = ImageTk.PhotoImage(titleimage)


		
		

		self.dFont=tkFont.Font(family="Arial", size=12, weight = 'bold')



		self.verticalFrame1 = Frame(self.r, height = 40, width = 20, padx = 4, pady = 4, relief = 'groove')
		#self.verticalFrame1.pack(side = TOP)
		self.verticalFrame1.grid(column = 1, row = 1, sticky=(N, W, E, S))

		self.verticalFrame2 = Frame(self.r, height = 40, width = 20, padx = 4, pady = 4, relief = 'groove')
		#self.verticalFrame2.pack(side = TOP)
		self.verticalFrame2.grid(column = 1, row = 2, sticky=(N, W, E, S))

		self.verticalFrame3 = Frame(self.r, height = 20, width = 20, padx = 4, pady = 8, relief = 'groove')
		#self.verticalFrame2.pack(side = TOP)
		self.verticalFrame3.grid(column = 1, row = 3, sticky=(N, W, E, S))


		#displaying top banner
		picLabel = Label(self.verticalFrame1, image=photo, pady = 6)
		picLabel.image = photo # keep a reference!
		picLabel.pack(side = TOP)


		
		
		#roxycheck = Checkbutton (self.verticalFrame3, variable = self.ifProxy , text = "westChamber Proxy", command = self.toggleProxy)
		#roxycheck.pack(side = LEFT)


		MODES = [("None", "none"),("WestChamberProxy", WCHAMBER),("goagent", GOAGENT)]

		v = StringVar()
		v.set("None")

		def changeproxy():
			global globalproxy
			print 'before setting: ', globalproxy
			globalproxy =  v.get()
			print 'after setting' , globalproxy
		

		for text, mode in MODES:
			b = Radiobutton(self.verticalFrame3, text=text,variable=v, value=mode, command = changeproxy, padx = 4)
			b.pack(side = RIGHT)


		

		self.searchQuery = StringVar()
		self.searchQuery.set("none")


		self.searchbar = Entry(self.verticalFrame3 )
		self.searchbar.pack(side = LEFT)
		self.searchbar.bind('<Return>', self.search_piratebay)



		searchButton = Button (self.verticalFrame3, text = "search", padx = 10, command = self.search_piratebay2)
		searchButton.pack(side = LEFT)


		self.f1 = Frame(self.verticalFrame2, height = 20, width = 20, padx = 4, pady = 4, relief = 'groove')
		self.f1.pack(side = LEFT)
		#self.f1.grid(row = 0, column = 0)


		#listbox for displaying magnet categories
		self.lb = Listbox (self.f1, name = 'lb', height = 18, width = 15, selectmode = SINGLE, font=('Arial',10,'bold'))
		self.lb.pack(side = LEFT)
		#self.lb.grid(row = 1 , column = 1)

		sbar2 = Scrollbar(self.f1)	
		sbar2.pack(side=RIGHT,fill=Y)
		self.lb.config(yscrollcommand=sbar2.set)
		
		sbar2.config(command=self.lb.yview)


		catList = grabrss.grabURL(globalproxy)
		for name, url in catList:
			self.lb.insert(END, name)

    

		self.f2 = Frame(self.verticalFrame2, height = 20, width = 60, padx = 4, pady = 4, relief = 'groove')
		self.f2.pack(side = RIGHT)
		#self.f2.grid(row = 1, column = 0)



		sbar = Scrollbar(self.f2)	
		sbar.pack(side=RIGHT,fill=Y)
		#content.pack(side=RIGHT, fill=Y)
		
		

		#displaying title and magnet
		self.text = Text(self.f2, height = 20, width = 65)
		self.text.pack(side = LEFT, fill = BOTH)
		self.text.bind('<Button-3>', self.rightClick)

		
		self.text.config(yscrollcommand=sbar.set)
		
		sbar.config(command=self.text.yview)
		sbar.pack(side=RIGHT, fill=Y)
		
		def bind(widget, event):
			def decorator(func):
				widget.bind(event, func)
				return func
			return decorator	   


		@bind(self.lb, '<<ListboxSelect>>')
		def onselect(evt):
			w = evt.widget
			index = int(w.curselection()[0])

			#print 'index is %d' % index
			name,fetchURL = catList[index]
			#print 'fetching URL: ', fetchURL
			self.loadURL(fetchURL)

		#fetch rssList
	
		
	"""
		def toggleProxy(self):

			


			global WCHAMBER
			global globalproxy

			print 'toggling proxy setting, was: ', globalproxy

			if self.ifProxy.get() == 0:
				
				globalproxy = 'none'

			else:
				globalproxy = WCHAMBER
				

			print 'now proxy is: ', globalproxy
			
"""		
	

	def loadURL(self, url):
		global globalproxy

		titleAndMagList = getItem.getItemsFromURL(globalproxy, url)
		
		#clean the window
		self.text.delete( 1.0, END)

		i = 1
		for title, link in titleAndMagList:

			self.text.insert(END, title + '\n' + link + '\n\n')

			start = "%d.0" % i
		 	end = "%d.%d" % (i, len(title))

		 	print start
		 	print end
		    
			self.text.tag_add("here", start, end)
			self.text.tag_config("here", background="yellow", font = self.dFont)

			i += 3

			print title, " : " , url


		#content.insert( END, quote)

		#b= Button(self.r, text = "hjell", command = self.r.destroy).pack()

	def search_piratebay(self, event):

		url = r'http://thepiratebay.se/search/###/0/7/0'

		self.searchQuery = self.searchbar.get()

		query1 = re.sub('\s','%20', self.searchQuery)
		query2 = re.sub('###', query1, url)
		print query2

		webbrowser.open_new(query2)


	def search_piratebay2(self):

		url = r'http://thepiratebay.se/search/###/0/7/0'

		self.searchQuery = self.searchbar.get()

		query1 = re.sub('\s','%20', self.searchQuery)
		query2 = re.sub('###', query1, url)
		print query2

		webbrowser.open_new(query2)



	def rightClick(self, event = None):
		"""
		a right click on selected text on 
		text widget will trigger this fucntion

		"""

		popup = Menu(root, tearoff=0)
		popup.add_command(label="Copy", command = self.copyText) # , command=next) etc...
		popup.add_command(label="search IMDB", command = self.searchIMDB)
		popup.add_command(label="search LastFM", command = self.searchLastFM)

		try:
			popup.tk_popup(event.x_root, event.y_root, 0)
		finally:
			# make sure to release the grab (Tk 8.0a1 only)
			popup.grab_release()
	
	def searchIMDB(self, event = None ) :
		#http://www.imdb.com/find?q=girl+with+machine&s=all
		url = r'http://www.imdb.com/find?q='
		

		try:
			text = self.text.get("sel.first", "sel.last")
			query1 = re.sub('\.','+',text)
			query = r'%s%s&s=all' % (url, query1)
			webbrowser.open_new(query)
		except:
			tkMessageBox.showerror('ERROR', "you did not select any text")

	def searchLastFM(self, event = None):
		#http://www.last.fm/search?q=The+Script+&from=ac
		url = r'http://www.last.fm/search?q='
		try:
			text = self.text.get("sel.first", "sel.last")
			query1 = re.sub('\s','+',text)
			query = r'%s%s&from=ac' % (url, query1)
			webbrowser.open_new(query)
		except:
			tkMessageBox.showerror('ERROR', "you did not select any text")


	def copyText(self, event = None):

			self.r.clipboard_clear()
			try:
				text = self.text.get("sel.first", "sel.last")
				self.r.clipboard_append(text)
			except:
				tkMessageBox.showerror('ERROR', "you did not select any text")

		

	def exit(self):
		self.r.destroy()


if __name__ == '__main__':
	
	root  = Tk()
	root.wm_resizable(FALSE, FALSE)
	root.title("pyGrab")
	#root.geometry("600x600")
	print 'start'
	app = myApp (root)
	print 'end'
	root.mainloop()
	


"""

	#permutate scroll list with options
	rssTupList = grabrss.grabURL(WCHAMBER)
	print rssTupList

	

	counter = 0
	for title, feed in rssTupList:
		print "%d. %s" % (counter , title )
		counter += 1
	myOption = raw_input("which one do you want to grab? ")
	myOption = int(myOption)
	
	if myOption >= 0:	

		title, url = rssTupList[myOption]
		print title, " : " , 	url
		titleAndMagList = getItem.getItemsFromURL(WCHAMBER, url)

		for title, link in titleAndMagList:
			print title
			print link
			print '\n'
	else:
		tkMessageBox.showerror("ERROR", "invalid option")
		exit(0)

		"""
	
	